package com.zpkj.portal.utils;

import java.lang.reflect.Type;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.zpkj.portal.utils.des3.Des3H5;
import com.zpkj.portal.utils.des3.Des3Utils;

public class JsonUtils {
	private static final Logger logger = LoggerFactory.getLogger(JsonUtils.class);
	/**
	 * 对象转换成json字符串
	 * 
	 * @param obj
	 * @return
	 */
	public static String toJson(Object obj) {
		Gson gson = new Gson();
		return gson.toJson(obj);
	}

	/**
	 * json字符串转成对象
	 * 
	 * @param str
	 * @param type
	 * @return
	 */
	public static <T> T fromJson(String str, Type type) {
		Gson gson = new Gson();
		return gson.fromJson(str, type);
	}

    public static Map<String, String> fromJson(String params){
        if(params == null){
            return null;
        }
        return JsonUtils.fromJson(params, new TypeToken<Map<String, String>>() {}.getType());
    }

	/**
	 * json字符串转成对象
	 * 
	 * @param str
	 * @param type
	 * @return
	 */
	public static <T> T fromJson(String str, Class<T> type) {
		Gson gson = new Gson();
		return gson.fromJson(str, type);
	}
	
	/**
	 * json字符串转成对象
	 * 
	 * requestType 3 H5
	 */
	public static <T> T fromEncryptJson(String str, Class<T> type,String requestSource) throws Exception {
		String decodeJsonStr = "";
		//h5的加密方式 3 ajax请求 4-ang请求 主要是返回数据格式不一样
		if( "3".equals(requestSource)||"4".equals(requestSource) ){
			Des3H5 des = new Des3H5();
			decodeJsonStr = des.decrypt(str);
		}	
		else{
			decodeJsonStr = Des3Utils.decode(str);
		}
		logger.info("解密入参jsonParams:{} ",decodeJsonStr);
		Gson gson = new Gson();
		return gson.fromJson(decodeJsonStr, type);
	}

	/**
	 * json字符串转成对象 不解密
	 * 
	 * requestType 3 H5
	 */
	public static <T> T fromEncryptJson(String str, Class<T> type) throws Exception {
	
		logger.info("入参jsonParams:{} ",str);
		Gson gson = new Gson();
		return gson.fromJson(str, type);
	}
	
}
